/**
 * @param {number[][]} grid
 * @return {boolean}
 */
var checkValidGrid = function (grid) {
  let len = grid.length
  let index = 0,
    row,
    col
  if (grid[0][0] == 0) {
    row = 0
    col = 0
  } else if (grid[0][len - 1] == 0) {
    row = 0
    col = len - 1
  } else if (grid[len - 1][0] == 0) {
    row = len - 1
    col = 0
  } else if (grid[len - 1][len - 1] == 0) {
    row = len - 1
    col = len - 1
  }
  while (index < len * len) {
    index++
    if (row + 2 < len) {
      if (col + 1 < len) {
        if (grid[row + 2][col + 1] == index) {
          row += 2
          col += 1

          continue
        }
      }
      if (col - 1 >= 0) {
        if (grid[row + 2][col - 1] == index) {
          row += 2
          col -= 1

          continue
        }
      }
    }

    if (row - 2 >= 0) {
      if (col + 1 < len) {
        if (grid[row - 2][col + 1] == index) {
          row -= 2
          col += 1

          continue
        }
      }
      if (col - 1 >= 0) {
        if (grid[row - 2][col - 1] == index) {
          row -= 2
          col -= 1

          continue
        }
      }
    }
    if (col - 2 >= 0) {
      if (row + 1 < len) {
        if (grid[row + 1][col - 2] == index) {
          row += 1
          col -= 2

          continue
        }
      }
      if (row - 1 >= 0) {
        if (grid[row - 1][col - 2] == index) {
          row -= 1
          col -= 2

          continue
        }
      }
    }
    if (col + 2 < len) {
      if (row + 1 < len) {
        if (grid[row + 1][col + 2] == index) {
          row += 1
          col += 2

          continue
        }
      }
      if (row - 1 >= 0) {
        if (grid[row - 1][col + 2] == index) {
          row -= 1
          col += 2

          continue
        }
      }
    }
    return index == len * len ? true : false
  }

  return true
}

checkValidGrid([
  [24, 11, 22, 17, 4],
  [21, 16, 5, 12, 9],
  [6, 23, 10, 3, 18],
  [15, 20, 1, 8, 13],
  [0, 7, 14, 19, 2],
])
